package dao

import (
	"fmt"
	"osiris/db"
	"osiris/dto"
	"osiris/logger"
	"osiris/model"
)

func GetAllLocal() ([]model.LocalModel, error) {
	var localModels []model.LocalModel
	err := db.MySQL.Find(&localModels).Error
	return localModels, err
}

func AddLocalByModel(model model.LocalModel) error {
	err := db.MySQL.Create(&model).Error
	if err != nil {
		logger.Error(map[string]interface{}{"[dao] [Add local by model]": err})
		return err
	}

	logger.Info(map[string]interface{}{"[dao] [Add local by model]": "success"})
	return nil
}

func DeleteLocal(accountAddrStr string) error {
	err := db.MySQL.Delete(&model.LocalModel{}, "addr = ?", accountAddrStr).Error
	return err
}

// TruncateLocals 硬删除Locals中所有数据
//
//	@return error
func TruncateLocals() error {
	return db.MySQL.Exec(fmt.Sprintf("truncate %s", model.LocalModel{}.TableName())).Error
}

func GetAllLocalQueued() ([]model.LocalQueuedModel, error) {
	var localQueuedModels []model.LocalQueuedModel
	err := db.MySQL.Find(&localQueuedModels).Error
	return localQueuedModels, err
}

func AddLocalQueuedByModel(model model.LocalQueuedModel) error {
	err := db.MySQL.Create(&model).Error
	if err != nil {
		logger.Error(map[string]interface{}{"[dao] [Add local queued tx by model]": err})
		return err
	}

	logger.Info(map[string]interface{}{"[dao] [Add local queued tx by model]": "success"})
	return nil
}

func AddLocalQueuedByTxData(txData dto.TxData) error {
	localQeuuedModel, err := txData.ToLocalQueuedModel()
	if err != nil {
		logger.Error(map[string]interface{}{"[dao] [Add local queued tx by txData]": err})
		return err
	}

	return AddLocalQueuedByModel(*localQeuuedModel)
}

func SaveLocalQueued(localQueued model.LocalQueuedModel) error {
	err := db.MySQL.Save(&localQueued).Error
	return err
}

func DeleteLocalQueued(txHash string) error {
	err := db.MySQL.Delete(&model.LocalQueuedModel{}, "txHash = ?", txHash).Error
	return err
}

// DeleteAllLocalQueued 软删除LocalQueued中所有数据
//
//	@return error
func DeleteAllLocalQueued() error {
	return db.MySQL.Where("1=1").Delete(&model.LocalQueuedModel{}).Error
}

// TruncateLocalQueued 硬删除LocalQueued中所有数据
//
//	@return error
func TruncateLocalQueued() error {
	return db.MySQL.Exec(fmt.Sprintf("truncate %s", model.LocalQueuedModel{}.TableName())).Error
}
